// ds1302_extended.c
#include "ds1302_extended.h"
#include "ds1302.h"
#include "esp_log.h"
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

// 记录上次同步的时间
static precise_time_t last_sync_time = {0};
static TickType_t last_sync_tick = 0;  // RTOS tick计数

// 初始化时间功能
esp_err_t ds1302_precise_init(void) {
    esp_err_t err;
    err = ds1302_init();
    if (err != ESP_OK) return err;

    // 强制初始化时间（无论是否有效）
    ESP_LOGI("DS1302", "Forcing time initialization to 2025-05-18 00:00:00");
    err = ds1302_initialize_time();
    if (err != ESP_OK) {
        ESP_LOGE("DS1302", "Failed to initialize default time");
        return err;
    }

    // 重新读取时间
    time_t seconds;
    err = ds1302_get_timestamp(&seconds);
    if (err != ESP_OK) return err;

    // 记录同步时间
    last_sync_time.seconds = seconds;
    last_sync_time.milliseconds = 0;
    last_sync_tick = xTaskGetTickCount();

    return ESP_OK;
}
// 设置时间
esp_err_t ds1302_set_precise_time(precise_time_t time) {
    // 设置DS1302的秒级时间
    esp_err_t err = ds1302_set_time_from_timestamp(time.seconds);
    if (err != ESP_OK) {
        return err;
    }

    // 记录当前同步时间和系统tick
    last_sync_time = time;
    last_sync_tick = xTaskGetTickCount();

    return ESP_OK;
}

// 获取时间（毫秒级精度）
esp_err_t ds1302_get_precise_time(precise_time_t *time) {
    if (!time) return ESP_ERR_INVALID_ARG;

    // 从DS1302读取秒级时间
    time_t seconds;
    esp_err_t err = ds1302_get_timestamp(&seconds);
    if (err != ESP_OK) {
        return err;
    }

    // 获取当前系统tick
    TickType_t current_tick = xTaskGetTickCount();

    // 计算自上次同步以来的毫秒数
    uint32_t elapsed_ms = (current_tick - last_sync_tick) * portTICK_PERIOD_MS;

    // 如果秒数已更新，重新同步
    if (seconds != last_sync_time.seconds) {
        last_sync_time.seconds = seconds;
        last_sync_time.milliseconds = 0;
        last_sync_tick = current_tick;
        time->seconds = seconds;
        time->milliseconds = 0;
    } else {
        // 否则，基于上次同步时间计算当前毫秒数
        time->seconds = seconds;
        time->milliseconds = (last_sync_time.milliseconds + elapsed_ms) % 1000;
    }

    return ESP_OK;
}

// 格式化输出（毫秒级）
char* ds1302_precise_time_to_string(precise_time_t time, char *buffer, size_t buffer_size) {
    if (!buffer || buffer_size < 30) {
        return NULL;
    }

    struct tm *tm_info;
    tm_info = localtime(&time.seconds);

    // 格式: YYYY-MM-DD HH:MM:SS.fff
    strftime(buffer, buffer_size, "%Y-%m-%d %H:%M:%S.", tm_info);
    char ms_str[4];
    snprintf(ms_str, 4, "%03d", time.milliseconds);
    strncat(buffer, ms_str, buffer_size - strlen(buffer) - 1);

    return buffer;
}